package com.ivan.toolkit.common;

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Objects;

import javax.imageio.ImageIO;

import lombok.Setter;

public class Ajax2 {
	
	@Setter
	private String url;
	
	@Setter
	private String charset = "UTF-8";
	
	@Setter
	private boolean radom = true;
	
	@Setter
	private int connectTimeout = 5000;
	
	@Setter
	private int readTimeout = 5000;
	
	@Setter
	private String method = "GET";
	
	private Map<String, String> parameters;
	
	public void setUrl(String home, String path) {
		
	}
	
	public void addParameter(String key, Object value) {
		parameters.put(key, Objects.toString(value));
	}
	
	public void removeParameter(String key) {
		parameters.remove(key);
	}

	public void clearParameter() {
		parameters.clear();
	}

    private HttpURLConnection execute()  
            throws IOException {
    	
        HttpURLConnection urlConnection = null;  
   
        String urlString = url;
        if (method.equalsIgnoreCase("GET") && parameters != null) {  
            StringBuffer param = new StringBuffer();  
            int i = 0;  
            for (String key : parameters.keySet()) {  
                if (i == 0)  
                    param.append("?");  
                else  
                    param.append("&");  
                param.append(key).append("=").append(parameters.get(key));  
                i++;  
            }  
            urlString += param;  
        }  
        
        URL url = new URL(urlString);  
        urlConnection = (HttpURLConnection) url.openConnection();   
   
        urlConnection.setRequestMethod(method);  
        urlConnection.setDoOutput(true);  
        urlConnection.setDoInput(true);  
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(connectTimeout);
        urlConnection.setReadTimeout(readTimeout);
        
        config(urlConnection);
   
        if (method.equalsIgnoreCase("POST") && parameters != null) {  
            StringBuffer param = new StringBuffer();  
            for (String key : parameters.keySet()) {  
                param.append("&");  
                param.append(key).append("=").append(parameters.get(key));  
            }  
            urlConnection.getOutputStream().write(param.toString().getBytes());  
            urlConnection.getOutputStream().flush();  
            urlConnection.getOutputStream().close();  
        }  
        
        return urlConnection; 
    }
    
    public HttpURLConnection get() throws Exception {
    	return this.execute();
    }
    
    public String getString(String charset) throws Exception {
    	
    	HttpURLConnection connection = this.execute();

        BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        byte[] arr = new byte[1024];
        while((len=bis.read(arr))!= -1){
            bos.write(arr,0,len);
            bos.flush();
        }
        bos.close();
        
    	return bos.toString(charset);
    }
    
    public byte[] getBytes() throws Exception {
    	
    	HttpURLConnection connection = this.execute();

        BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        byte[] arr = new byte[1024];
        while((len=bis.read(arr))!= -1){
            bos.write(arr,0,len);
            bos.flush();
        }
        bos.close();
        
    	return bos.toByteArray();
    	
    }
    
    public Image getImage() throws Exception {
    	
    	HttpURLConnection connection = this.execute();    	
    	return ImageIO.read(connection.getInputStream());
    	
    }
    
    public void downloadFile(File file) throws Exception {
    	
    	HttpURLConnection connection = this.execute();
    	
    	InputStream source = connection.getInputStream();
    	
    	if(file.exists()) {
    		file.delete();
    	}
    	FileOutputStream sink = new FileOutputStream(file);
    	
        byte[] buf = new byte[4096];
        int n;
        while ((n = source.read(buf)) > 0) {
            sink.write(buf, 0, n);
        }
        
        sink.close();
        sink = null;
    	
    }
    
    
    protected void config(HttpURLConnection httpUrlConnection) {}

}
